package cn.getech.data.metadata.utils;

import cn.getech.data.metadata.constant.WeekEnum;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

public class CronUtils {
    //"ss mm HH dd MM ? yyyy"
    private static final SimpleDateFormat sdf = new SimpleDateFormat("ss mm HH dd MM ?");

    /***
     *  功能描述：日期转换cron表达式
     * @param date
     * @return
     */
    public static String formatDateByPattern(Date date) {
        String formatTimeStr = null;
        if (Objects.nonNull(date)) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }

    /***
     * convert Date to cron, eg "0 07 10 15 1 ?"
     * @param date  : 时间点
     * @return
     */
    public static String getCron(Date date) {
        return formatDateByPattern(date);
    }

    public static String getCronExpression(int rate, String cycle) {
        String cron = "";
        String[] split = cycle.split(" ");
        switch (rate) {
            case 1:// 每cycle分钟执行一次
                cron = "0 0/" + cycle + " * * * ?";
                break;
            case 2:// 每cycle小时执行一次
                cron = "0 0 0/" + cycle + " * * ?";
                break;
            case 3:// 每小时几分执行
                cron = "0 " + cycle + " 0/1 * * ?";
                break;
            case 4:// 每日几时几分
                cron = "0 " + split[0] + " " + split[1] + " 0/1 * ?";
                break;
            case 5:// 每周周几的几时几分
                String weekDay = WeekEnum.getWeekDay(Integer.parseInt(split[2]));
                cron = "0 " + split[0] + " " + split[1] + " ? * " + weekDay;
                break;
            case 6:// 每月的几号几时几分
                cron = "0 " + split[0] + " " + split[1] + " " + split[2] + " * ? ";
                break;
            default:// 默认每cycle小时执行一次
                cron = "0 0/ *" + cycle + " * * ?";
                break;
        }
        return cron;
    }

    public static String getCronDescription(int rate, String cycle) {
        String desc = "";
        String[] split = cycle.split(" ");
        switch (rate) {
            case 1:
                desc = "每隔" + cycle + "分钟";
                break;
            case 2:
                desc = "每隔" + cycle + "小时";
                break;
            case 3:// 每小时几分执行
                desc = "每小时" + cycle + "分";
                break;
            case 4:// 每日几时几分
                desc = "每日" + split[1] + "时" + split[0] + "分";
                break;
            case 5:// 每周周几的几时几分
                String weekDay = WeekEnum.getWeek(Integer.parseInt(split[2]));
                desc = "每周" + weekDay + split[1] + "时" + split[0] + "分";
                break;
            case 6:// 每月的几号几时几分
                desc = "每月" + split[2] + "号" + split[1] + "时" + split[0] + "分";
                break;
            default://每cycle小时执行一次
                desc = "每隔" + cycle + "分钟";
                break;
        }
        return desc;
    }
}
